﻿using System;
using System.Collections.Generic;
using MyHealthByDesign.Domain;
using System.Web.UI.WebControls;

namespace MyHealthByDesign.Admin
{
    /// <summary>
    /// Description:
    /// Displays website question maintenance for the administration section
    /// 
    /// Author: Mark Servais
    /// Date Created: 12/03/2011
    /// 
    /// Other code files referenced:
    /// None.
    /// 
    /// Regression Test Information:
    /// None.
    /// 
    /// Revision History:
    /// None. 
    /// 
    /// Known Faults:
    /// None.
    /// </summary>
    public partial class MaintainQuestions : System.Web.UI.Page
    {
        Domain.Domain domain = new Domain.Domain();

        /// <summary>
        /// Page Init event handler - load question panels
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Controls loaded for programatic access
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            if (Session["DisplayType"] != null)
            {
                if (Session["DisplayType"] != string.Empty)
                {
                    // insert form
                    Question question = new Question();
                    question.DisplayType = (string) Session["DisplayType"];

                    List<Panel> panels = new List<Panel>();

                    panels.Add(pnlProcessingRules);
                    panels.Add(pnlOptions);
                    panels.Add(pnlQuestionCore);

                    panels = question.GenerateAdminPanels(panels);

                    foreach (Panel p in panels)
                    {
                        switch (p.ID)
                        {
                            case "pnlProcessingRules":
                                pnlProcessingRules = p;
                                break;
                            case "pnlOptions":
                                pnlOptions = p;
                                break;
                            case "pnlQuestionCore":
                                pnlQuestionCore = p;
                                break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Page Load event handler - check if admin is logged in
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Page displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!domain.IsAdminLoggedIn())
            {
                Response.Redirect("Default.aspx");
            }

            if (!Page.IsPostBack)
            {
                // load list box
                LoadCategoryList();

                // set button visibility
                ResetButtons();

                if (Request.QueryString["c"] != null && Request.QueryString["q"] != null)
                {
                    foreach (ListItem item in ddlCategories.Items)
                    {
                        item.Selected = (item.Value == (string)Request.QueryString["c"]);
                    }

                    ddlCategories_SelectedIndexChanged(new object(), new EventArgs());

                    foreach (ListItem item in lbQuestions.Items)
                    {
                        item.Selected = (item.Value == (string)Request.QueryString["q"]);
                    }

                    lbQuestions_SelectedIndexChanged(new object(), new EventArgs());

                }
            }
        }

        /// <summary>
        /// LoadCategoryList - populates categories in list box fo maintenance
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Page displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LoadCategoryList()
        {
            ddlCategories.Items.Clear();

            List<QuestionCategory> lstCategories = domain.GetCategories();

            // add database items
            foreach (var questionCategory in lstCategories)
            {
                ddlCategories.Items.Add(new ListItem(questionCategory.CategoryDescription, questionCategory.CategoryId.ToString()));
            }

            ddlCategories.Items[0].Selected = true;

            // Load initial question list
            LoadQuestionList();
        }

        /// <summary>
        /// ResetButtons - resets maintenance buttons
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Page displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ResetButtons()
        {
            
            lblErrors.Visible = false;
            btnMoveUp.Visible = false;
            btnMoveDown.Visible = false;
            btnDelete.Visible = false;
            btnOptions.Visible = false;

            pnlQuestionCore.Controls.Clear();
            pnlProcessingRules.Controls.Clear();
            pnlOptions.Controls.Clear();
            pnlSubmit.Visible = false;
        }

        /// <summary>
        /// ddlCategories_SelectedIndexChanged - category selection made
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are loaded and displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadQuestionList();
            ResetButtons();
        }

        /// <summary>
        /// lbQuestions_SelectedIndexChanged - question selection made
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are loaded and displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbQuestions_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnlQuestionCore.Controls.Clear();
            pnlProcessingRules.Controls.Clear();
            pnlOptions.Controls.Clear();

            if (lbQuestions.SelectedIndex == 0)
            {
                btnMoveUp.Visible = false;
                btnMoveDown.Visible = false;

                // other addition tasks
                btnDelete.Visible = false;
                btnOptions.Visible = false;
                pnlQuestionCore.Visible = false;
                pnlSubmit.Visible = false;

                Session["DisplayType"] = string.Empty;

                // force new display type selection prior to any form display
                pnlDisplaySelect.Visible = true;
            }
            else
            {
                if (lbQuestions.SelectedIndex == 1)
                    btnMoveUp.Visible = false;
                else
                    btnMoveUp.Visible = true;

                if (lbQuestions.SelectedIndex == (lbQuestions.Items.Count - 1))
                    btnMoveDown.Visible = false;
                else
                    btnMoveDown.Visible = true;

                btnDelete.Visible = true;
                pnlSubmit.Visible = true;
                pnlDisplaySelect.Visible = false;
                

                
                // update form
                Question question = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.SelectedValue));
                Session["DisplayType"] = question.DisplayType;

                if (question.FieldOptions.Count > 0)
                    btnOptions.Visible = true;
                else
                    btnOptions.Visible = false;
                

                List<Panel> panels = new List<Panel>();

                panels.Add(pnlProcessingRules);
                panels.Add(pnlOptions);
                panels.Add(pnlQuestionCore);

                panels = question.GenerateAdminPanels(panels);

                foreach (Panel p in panels)
                {
                   switch(p.ID)
                   {
                       case "pnlProcessingRules":
                           pnlProcessingRules = p;
                           break;
                       case "pnlOptions":
                           pnlOptions = p;
                           break;
                       case "pnlQuestionCore":
                           pnlQuestionCore = p;
                           break;
                   }
                }
                
                pnlQuestionCore.Visible = true;
               
            }


        }

        /// <summary>
        /// LoadQuestionList - populates categories in list box fo maintenance
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Page displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LoadQuestionList()
        {
            lbQuestions.Items.Clear();

            // add first item
            lbQuestions.Items.Add(new ListItem("<Add new Question>", "AA"));


            List<Question> lstQuestions = domain.RetrieveQuestions(Convert.ToInt32(ddlCategories.SelectedValue));

            // add database items
            foreach (var question in lstQuestions)
            {
                lbQuestions.Items.Add(new ListItem(question.ContentLabel, question.Id.ToString()));
            }

            foreach (ListItem item in lbQuestions.Items)
            {
                item.Attributes.Add("title", item.Text);
            }

        }

        
        /// <summary>
        /// btnMoveUp_Click - update question sort
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are loaded and displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMoveUp_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            // get selected question
            Question selectedQuestion = new Question();
            selectedQuestion = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.SelectedValue));

            // get previous question in the list
            Question swapQuestion = new Question();
            swapQuestion = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.Items[lbQuestions.SelectedIndex - 1].Value));

            // swap sort order
            int selectedOrder = selectedQuestion.SortOrder;
            selectedQuestion.SortOrder = swapQuestion.SortOrder;
            swapQuestion.SortOrder = selectedOrder;

            // update each question
            domain.UpdateQuestionCore(swapQuestion);
            domain.UpdateQuestionCore(selectedQuestion);

            // rebuild list box
            LoadQuestionList();
            ResetButtons();
        }

        /// <summary>
        /// btnMoveDown_Click - update question sort
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are loaded and displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMoveDown_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            // get selected question
            Question selectedQuestion = new Question();
            selectedQuestion = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.SelectedValue));

            // get previous question in the list
            Question swapQuestion = new Question();
            swapQuestion = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.Items[lbQuestions.SelectedIndex + 1].Value));

            // swap sort order
            int selectedOrder = selectedQuestion.SortOrder;
            selectedQuestion.SortOrder = swapQuestion.SortOrder;
            swapQuestion.SortOrder = selectedOrder;

            // update each question
            domain.UpdateQuestionCore(swapQuestion);
            domain.UpdateQuestionCore(selectedQuestion);

            // rebuild list box
            LoadQuestionList();
            ResetButtons();
        }

        /// <summary>
        /// btnDelete_Click - delete question
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Appropriate questions are flagged as deactivated
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            // get selected question
            Question selectedQuestion = new Question();
            selectedQuestion = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.SelectedValue));

            selectedQuestion.SortOrder = 0;
            
            // update question
            domain.UpdateQuestionCore(selectedQuestion);
            domain.UpdateQuestionStatus(Convert.ToInt32(lbQuestions.SelectedValue));

            // rebuild list box
            LoadQuestionList();
            ResetButtons();
        }

        /// <summary>
        /// btnSubmit_Click - submit Question form
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Form submitted for processing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Question question;

            if (lbQuestions.SelectedValue == "AA")
            {
                question = new Question();
                question.DisplayType = (string)Session["DisplayType"];
            }
            else
            {
                question = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.SelectedValue)); 
            }

            List<Panel> panels = new List<Panel>();

            panels.Add(pnlProcessingRules);
            panels.Add(pnlOptions);
            panels.Add(pnlQuestionCore);

            question.ProcessAdminPanels(panels);

            LoadQuestionList();
            ResetButtons();
            Session["DisplayType"] = null;
        }

        /// <summary>
        /// btnSubmitDisplay_Click - select display type for Question on add
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// Form submitted for processing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmitDisplay_Click(object sender, EventArgs e)
        {
            Session["DisplayType"] = ddlSelectDisplay.SelectedValue;
            pnlDisplaySelect.Visible = false;

            pnlSubmit.Visible = true;

            // add form
            Question question = new Question();
            question.DisplayType = (string)Session["DisplayType"];

            List<Panel> panels = new List<Panel>();

            panels.Add(pnlProcessingRules);
            panels.Add(pnlOptions);
            panels.Add(pnlQuestionCore);

            panels = question.GenerateAdminPanels(panels);

            foreach (Panel p in panels)
            {
                switch (p.ID)
                {
                    case "pnlProcessingRules":
                        pnlProcessingRules = p;
                        break;
                    case "pnlOptions":
                        pnlOptions = p;
                        break;
                    case "pnlQuestionCore":
                        pnlQuestionCore = p;
                        break;
                }
            }

            pnlQuestionCore.Visible = true;

        }

        /// <summary>
        /// btnOptions_Click - edit options for question
        /// 
        /// PreConditions:
        /// None
        /// 
        /// PostConditions:
        /// redirected to optoins maintenance
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOptions_Click(object sender, EventArgs e)
        {
            Question question = domain.RetrieveQuestion(Convert.ToInt32(lbQuestions.SelectedValue));

            Session["OptionQuestionID"] = question.Id;
            Session["OptionQuestionCategoryID"] = question.Category;

            Response.Redirect("MaintainOptions.aspx");
        }

        
    }
}